<template>
  <vxe-modal
    resize
    esc-closable
    width="55%"
    height="80%"
    showFooter
    v-model="formVisible"
    @hide="formClose"
    :loading="formLoading"
  >
    <template slot="title">
      <span>组织架构表单</span>
    </template>
    <template>
      <el-scrollbar class="scrollbar-handle">
        <vxe-form
          ref="firstForm"
          title-width="100"
          title-align="right"
          :data="formEntity"
          :rules="rules"
          span="12"
        >
          <vxe-form-item
            title="组织编码"
            field="B_EnCode"
            :title-suffix="{ message: '组织编码不能重复！', icon: 'fa fa-exclamation-circle' }"
          >
            <el-input v-model="formEntity.B_EnCode" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item
            title="组织名称"
            field="B_FullName"
            :title-suffix="{ message: '组织名称不能重复！', icon: 'fa fa-exclamation-circle' }"
          >
            <el-input v-model="formEntity.B_FullName" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item title="所属组织" :title-suffix="{ message: '非超管用户，所属组织必填！', icon: 'fa fa-exclamation-circle' }">        
            <rayd-select :options="manaTreeList" v-model="formEntity.B_ParentId" tree-config></rayd-select>
          </vxe-form-item>
          <vxe-form-item title="组织性质">
            <rayd-select options="ManaNature" v-model="formEntity.B_Nature" tree-config></rayd-select>
          </vxe-form-item>
          <vxe-form-item title="负责人" field="B_Manager">
            <el-input v-model="formEntity.B_Manager" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item title="电子邮箱" field="B_Email">
            <el-input v-model="formEntity.B_Email" placeholder="请输入" clearable></el-input>
          </vxe-form-item>
          <vxe-form-item title="所处地址">
            <el-cascader
              clearable
              filterable
              :props="{ expandTrigger: 'hover' }"
              :options="ssqTreeList"
              v-model="formEntity.SsqIds"
            ></el-cascader>
          </vxe-form-item>
          <vxe-form-item title="排序码" span="10">
            <el-input-number :controls="false" :min="0" v-model="formEntity.B_SortCode"></el-input-number>
          </vxe-form-item>
          <vxe-form-item title="详细地址" field="B_Address" span="24">
            <el-input placeholder="请输入" clearable v-model="formEntity.B_Address"></el-input>
          </vxe-form-item>
          <vxe-form-item title="描述" field="B_Description" span="24">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 4}"
              maxlength="50"
              show-word-limit
              placeholder="请输入"
              clearable
              v-model="formEntity.B_Description"
            ></el-input>
          </vxe-form-item>
        </vxe-form>
      </el-scrollbar>
    </template>
    <template slot="footer">
      <el-button type="primary" v-form-validate="formSubmit">保存</el-button>
      <el-button @click="formVisible=false">取消</el-button>
    </template>
  </vxe-modal>
</template>

<script>
import { mapGetters } from "vuex"; 
import { Manaframe, DataItem, Ssq } from "@/api";
export default {
  name: "Form",
  props: {},
  computed: {
    ...mapGetters(["userinfo"]),
  },
  data() {
    return {
      //存放表单ref数组
      formArr: ["firstForm"],
      //表单可见
      formVisible: false,
      //表单加载中
      formLoading: false,
      //表单实体
      formEntity: { SsqIds: [] },
      //表单验证规则（规则键必须和表单键一致）
      rules: {
        B_Email: [
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请输入正确的邮箱地址",
          },
        ],
        B_EnCode: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  Manaframe.ValidateExist({
                    id: this.formEntity.B_ManaframeId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("组织编码已存在！"));
                    });
                }
              });
            },
          },
        ],
        B_FullName: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  Manaframe.ValidateExist({
                    id: this.formEntity.B_ManaframeId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("组织名称已存在！"));
                    });
                }
              });
            },
          },
        ],
      },
      /* 实体数据 */
      manaTreeList: [], //组织树型数据
      natureTreeList: this.util.getDataItemList("ManaNature"), //组织性质树型数据（数据字典）
      ssqTreeList: [], //省市区树型数据
    };
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {
      /* 初始化数据源 */
      Promise.all([
        //获取省市区树形数据
        Ssq.GetTreeList().then((res) => {
          this.ssqTreeList = res;
        }),
      ]).then(() => {});
    },
    //表单开启
    formOpen(row) {
      //打开表单
      this.formVisible = this.formLoading = true;
      if (!row) {
        //新增
        this.formEntity.B_ParentId = this.userinfo.manaframeId;
        this.formEntity.B_SortCode = 0;
      } else {
        //编辑
        this.formEntity = JSON.parse(JSON.stringify(row));
        //级联选择器的数据回显处理（emitPath）
        let id = this.util.validateNull(this.formEntity.B_CountyId)
          ? this.util.validateNull(this.formEntity.B_CityId)
            ? this.formEntity.B_ProvinceId
            : this.formEntity.B_CityId
          : this.formEntity.B_CountyId; //深度id处理
        this.formEntity.SsqIds = this.util.getTreeDeepArr(id, this.ssqTreeList);
      }
      //获取组织树形数据
      Manaframe.GetTreeList(this.formEntity.B_ManaframeId).then((res) => {
        this.manaTreeList = res;
        this.formLoading = false;
      });
    },
    //表单提交
    formSubmit() {
          //关联架构
          if(!this.userinfo.isSystem && this.util.validateNull(this.formEntity.B_ParentId)){
            this.$message.warning("非超管用户，所属组织必填！");
            return;
          }
          //级联选择器的数据保存处理
          this.formEntity.B_ProvinceId = this.formEntity.SsqIds[0];
          this.formEntity.B_CityId = this.formEntity.SsqIds[1];
          this.formEntity.B_CountyId = this.formEntity.SsqIds[2];
          //验证通过
          Manaframe.Save(this.formEntity).then((res) => {
            this.formVisible = false; //关闭弹窗
            this.$emit("refresh"); //刷新表格
            //刷新缓存数据
            Manaframe.GetTreeList().then((res) => {
              this.$store.commit("SET_MANALIST", res);
            })
          });
    },
    //表单关闭
    formClose() {
      //清除表单验证
      this.util.formClearValid(this.formArr);
      //数据归位
      Object.assign(this.$data, this.$options.data.call(this))
    },
  },
};
</script>

<style lang="less" scoped>
</style>